package com.lixingye.meowstar.controller;

import com.lixingye.meowstar.common.AppResult;
import com.lixingye.meowstar.common.ResultCode;
import com.lixingye.meowstar.config.AppConfig;
import com.lixingye.meowstar.model.Article;
import com.lixingye.meowstar.model.Board;
import com.lixingye.meowstar.model.User;
import com.lixingye.meowstar.service.IArticleService;
import com.lixingye.meowstar.service.IBoardService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 猫大仙
 * @since 2025-01-14
 */
@Tag(name = "帖子接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private IArticleService articleService;
    @Autowired
    private IBoardService boardService;
    /**
     * 发布新帖子
     * @param boardId
     * @param title
     * @param content
     * @return
     */
    @Operation(summary = "发布新帖")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @Parameter(name ="boardId" ,description = "板块ID") @RequestParam("boardId") @NonNull Long boardId,
                            @Parameter(name ="title" ,description = "文章标题") @RequestParam("title") @NonNull String title,
                            @Parameter(name ="content" ,description = "文章内容") @RequestParam("content") @NonNull String content){
        //校验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1){
            //用户已禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //板块校验
        Board board = boardService.getById(boardId.longValue());
        if(board == null || board.getDeleteState()==1 || board.getState()==1){
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString() + ",板块已禁用,boardid= "+boardId);
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }
        //封装文章对象
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setBoardId(boardId);
        article.setUserId(user.getId());
        articleService.create(article);
        return AppResult.success();
    }

    @Operation(summary = "获取板块下所有帖子")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@Parameter(name ="boardId" ,description = "板块ID") @RequestParam(value = "boardId",required = false) Long boardId){
        List<Article> articles;
        if(boardId == null){
            articles = articleService.selectAll();
            if(articles == null) articles = new ArrayList<>();
        }else {
            articles = articleService.selectAllByBoardId(boardId);
            if(articles == null) articles = new ArrayList<>();
        }
        return AppResult.success(articles);
    }

    @Operation(summary = "获取帖子详情")
    @GetMapping("/getDetails")
    public AppResult<Article> getDetails(HttpServletRequest request,
            @Parameter(name = "id",description = "帖子ID") @RequestParam("id") @NonNull  Long id){
        //从session中获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        Article article = articleService.selectDetailById(id);

        if(article == null){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if(user.getId() == article.getUserId()){
            article.setOwn(true);
        }
        return AppResult.success(article);
    }
    @Operation(summary = "修改帖子")
    @PostMapping("/modify")
    public  AppResult modify(HttpServletRequest request,
                             @Parameter(description = "帖子ID") @RequestParam("id") Long id,
                             @Parameter(description = "帖子标题") @RequestParam("title") String title,
                             @Parameter(description = "帖子内容") @RequestParam("content") String content){
        //获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState()==1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //查询帖子详情
        Article article = articleService.selectbById(id);
        //判断帖子是否存在
        if(article == null){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断帖子是否属于当前用户
        if(user.getId() != article.getUserId()){
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //判断帖子是否可访问
        if(article.getState() == 1 || article.getDeleteState()==1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        articleService.modify(id,title,content);
        log.info("修改帖子成功,Article id="+id);
        //返回结果
        return AppResult.success(article);
    }
    @Operation(summary = "点赞")
    @PostMapping("/thumbsUp")
   public AppResult thumbsUpById(HttpServletRequest  request,
           @Parameter(description = "帖子ID") @RequestParam("id") @NonNull Long id){
        //校验
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断用户是否被禁言
        if(user.getState()==1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        articleService.thumbsUpById(id);
        return AppResult.success();
   }
    @Operation(summary = "删除帖子")
    @PostMapping("/delete")
   public AppResult deleteById(HttpServletRequest request,
                               @Parameter(description = "帖子ID") @RequestParam("id") @NonNull Long id){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState()==1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
       Article article = articleService.selectbById(id);
        //判断帖子是否存在
        if(article == null || article.getDeleteState()==1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //对比
        if(article.getUserId() != user.getId()){
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //校验均无问题,进行删除
        articleService.deleteById(id);
        return AppResult.success();
   }
    @Operation(summary = "获取用户帖子列表")
    @GetMapping("/getAllByUserId")
   public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                   @Parameter(description = "用户ID") @RequestParam(value = "userId",required = false) Long userId){
        //如果UserId为空,则从session中获取用户信息
        if(userId == null){
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        List<Article> articles = articleService.selectByUserId(userId);
        return AppResult.success(articles);
    }
}
